package pbl;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public class PersonHandler implements Runnable {

	Socket socket;
	List<Person> personList;
	
	public PersonHandler(Socket socket, List<Person> personList) {
		System.out.println("Setting up a PersonHandler");
		this.socket = socket;
		this.personList = personList;
	}
	
	public void run() 
	{
		try {
			InputStream is = socket.getInputStream();
		    ObjectInputStream ois = new ObjectInputStream( is );
		    
		    OutputStream os = socket.getOutputStream();
		    ObjectOutputStream oos = new ObjectOutputStream( os );
		    
		    int operation = (Integer) ois.readObject();
		    
		    if ( operation == 1 )
		    {
		    	System.out.println("Adding a Person to PersonServer");
		    	Person person = (Person) ois.readObject();
		    	personList.add(person);

		    }
		    if ( operation == 2 ) {
		    	int index = (Integer) ois.readObject();
		    	System.out.println("Fetching person at index "+index+ "from PersonServer");
		    	Person person = personList.get(index);
		    	oos.writeObject(person);
		    	oos.flush();
		    }
		    socket.close();
		}
		catch (Exception ignore) { }
	}
	
	
}
